package com.example.administrator.androidros.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.example.administrator.androidros.R;
import com.example.administrator.androidros.base.BaseActivity;
import com.example.administrator.androidros.model.ApplianceModel;
import com.example.administrator.androidros.net.HttpUtils;
import com.example.administrator.androidros.utils.AgentConstants;
import com.example.administrator.androidros.utils.AgentSharedPreferences;
import com.example.administrator.androidros.utils.DisplayHelper;
import com.example.administrator.androidros.utils.ServerConstants;
import com.example.administrator.androidros.utils.StringUtils;
import com.example.administrator.androidros.widget.CustomDialog;
import com.example.administrator.androidros.widget.CustomPopupMenu;
import com.example.administrator.androidros.widget.CustomTipDialog;
import com.example.administrator.androidros.widget.EditDialog;
import com.hhc.netty.DeviceModel;
import com.hhc.netty.NettyBaseMsg;
import com.hhc.netty.NettyClient;
import com.hhc.netty.NettyReplyStatusMsg;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class DeviceDetailsActivity extends BaseActivity {
    private static final String TAG = "hhc";
    @BindView(R.id.common_head_more)
    protected ImageView common_head_more;
    @BindView(R.id.common_head_title)
    protected TextView common_head_title;
    @BindView(R.id.activity_device_details_img_qrcode)
    protected ImageView activity_device_details_img_qrcode;
    @BindView(R.id.activity_device_details_img_appliance_name_loading)
    protected ImageView activity_device_details_img_appliance_name_loading;
    @BindView(R.id.activity_device_details_img_appliance_type_loading)
    protected ImageView activity_device_details_img_appliance_type_loading;
    @BindView(R.id.activity_device_details_img_scene_name_loading)
    protected ImageView activity_device_details_img_scene_name_loading;
    @BindView(R.id.activity_device_details_img_appliance_online_loading)
    protected ImageView activity_device_details_tv_appliance_online_loading;
    @BindView(R.id.activity_device_details_img_switch_loading)
    protected ImageView activity_device_details_img_switch_loading;

    @BindView(R.id.activity_device_details_tv_appliance_name)
    protected TextView activity_device_details_tv_appliance_name;
    @BindView(R.id.activity_device_details_tv_appliance_type)
    protected TextView activity_device_details_tv_appliance_type;
    @BindView(R.id.activity_device_details_tv_scene_name)
    protected TextView activity_device_details_tv_scene_name;
    @BindView(R.id.activity_device_details_tv_appliance_online)
    protected TextView activity_device_details_tv_appliance_online;
    @BindView(R.id.activity_device_details_switch)
    protected Switch activity_device_details_switch;

    private List<Integer> moreIconList = new ArrayList<>();//更多
    private List<String> moreTitleList = new ArrayList<>();

    private String masterId;
    private String applianceName;
    private String type;
    private ApplianceModel applianceModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_device_details);
    }

    @Override
    protected void initData() {
        getIntentData();
        initCommonHeader(applianceName);
        initView();
        initMoreData();
        initListener();
    }

    @Override
    protected void onFailure(int requestCode, Object object) {
        showToast(R.string.common_response_failure);
        stopTipDialog();
    }

    @Override
    protected void onSuccess(int requestCode, Object object) {
        stopTipDialog();
        if (object != null) {
            switch (requestCode) {
                case 1001:
                    //获取设备信息
                    applianceModel = (ApplianceModel) HttpUtils.getData(object, ApplianceModel.class);
                    if (applianceModel != null) {
                        updateApplianceMessage(applianceModel.getAppliancePic(), applianceModel.getApplianceName(), applianceModel.getApplianceType(), applianceModel.getSceneName());
                        getApplianceStatus(applianceModel.getMemberDeviceId(), applianceModel.getApplianceId());
                    }
                    break;
                case 1003:
                    //修改设备名称
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        getApplianceDetails();
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                case 1004:
                    //删除设备
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        finish();
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                default:
                    break;
            }
        }
    }

    protected void getIntentData() {
        // 获取意图对象
        Intent intent = getIntent();
        //获取传递的值
        masterId = intent.getStringExtra("masterId");
        applianceName = intent.getStringExtra("applianceName");
        type = intent.getStringExtra("type");
    }

    protected void initView() {
        Glide.with(mBaseActivity).load(R.drawable.loading_progress).into(activity_device_details_img_qrcode);
        Glide.with(mBaseActivity).load(R.drawable.loading_progress).into(activity_device_details_img_appliance_name_loading);
        Glide.with(mBaseActivity).load(R.drawable.loading_progress).into(activity_device_details_img_appliance_type_loading);
        Glide.with(mBaseActivity).load(R.drawable.loading_progress).into(activity_device_details_img_scene_name_loading);
        Glide.with(mBaseActivity).load(R.drawable.loading_progress).into(activity_device_details_tv_appliance_online_loading);
        Glide.with(mBaseActivity).load(R.drawable.loading_progress).into(activity_device_details_img_switch_loading);

        activity_device_details_tv_appliance_name.setVisibility(View.GONE);
        activity_device_details_tv_appliance_type.setVisibility(View.GONE);
        activity_device_details_tv_scene_name.setVisibility(View.GONE);
        activity_device_details_tv_appliance_online.setVisibility(View.GONE);
        activity_device_details_switch.setVisibility(View.GONE);
    }

    protected void initCommonHeader(String title) {
        common_head_more.setImageResource(R.mipmap.icon_more);
        if (type.equals("10")) {
            configCommonHeader(this, title, true);
        } else {
            configCommonHeader(this, title, false);
        }
    }

    protected void initMoreData() {
        moreIconList.add(R.mipmap.icon_homepage_select);
        moreIconList.add(R.mipmap.icon_my_select);
        moreTitleList.add(getString(R.string.device_title_change));
        moreTitleList.add(getString(R.string.device_delete));
    }


    protected void initListener() {
//        activity_device_details_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked) {
//                    //发送开的指令
//                    controlApplianceStatus("10", null);
//                } else {
//                    //发送关的指令
//                    controlApplianceStatus("20", null);
//                }
//            }
//        });

        activity_device_details_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(activity_device_details_switch.isChecked()){
                    controlApplianceStatus("10", null);
                }else {
                    //发送关的指令
                    controlApplianceStatus("20", null);
                }
            }
        });
    }

    //修改设备名称
    protected void updateApplianceName(String name) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("masterId", masterId);
        jsonObject.put("applianceName", name);
        HttpUtils.post(mBaseActivity, 1003, ServerConstants.UPDATE_APPLIANCE_NAME, jsonObject.toString(), mBaseActivity);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_changing), true);
    }

    //删除设备
    protected void deleteAppliance() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("masterId", masterId);
        HttpUtils.post(mBaseActivity, 1004, ServerConstants.DELETE_APPLIANCE, jsonObject.toString(), mBaseActivity);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_deleting), true);
    }

    //获取基本信息
    protected void getApplianceMessage() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("masterId", masterId);
        HttpUtils.post(mBaseActivity, 1001, ServerConstants.GET_APPLIANCE_MESSAGE, jsonObject.toString(), mBaseActivity);
    }

    //视图更新基本信息
    protected void updateApplianceMessage(String appliancePic, String applianceName, String applianceType, String sceneName) {
        activity_device_details_img_appliance_name_loading.setVisibility(View.GONE);
        activity_device_details_img_appliance_type_loading.setVisibility(View.GONE);
        activity_device_details_img_scene_name_loading.setVisibility(View.GONE);

        activity_device_details_tv_appliance_name.setVisibility(View.VISIBLE);
        activity_device_details_tv_appliance_type.setVisibility(View.VISIBLE);
        activity_device_details_tv_scene_name.setVisibility(View.VISIBLE);
        if (appliancePic != null && !appliancePic.equals("")) {
//            ViewGroup.LayoutParams params = activity_device_details_img_qrcode.getLayoutParams();
//            params.height = DisplayHelper.dpToPx(200);
//            params.width = DisplayHelper.dpToPx(200);
//            activity_device_details_img_qrcode.setLayoutParams(params);
            Glide.with(mBaseActivity).load(ServerConstants.FILE_SERVER_URL + appliancePic).into(activity_device_details_img_qrcode);
        }
        activity_device_details_tv_appliance_name.setText(applianceName);
        activity_device_details_tv_appliance_type.setText(StringUtils.getApplianceType(applianceType));
        if (sceneName != null && !sceneName.equals("")) {
            activity_device_details_tv_scene_name.setText(sceneName);
        } else {
            activity_device_details_tv_scene_name.setText("无");
        }
        common_head_title.setText(applianceName);
    }

    //视图更新设备状态
    protected void updateApplianceStatus(String onlineStatus, String status) {
        if (onlineStatus.equals("10")) {
            activity_device_details_tv_appliance_online_loading.setVisibility(View.GONE);
            activity_device_details_tv_appliance_online.setVisibility(View.VISIBLE);
            activity_device_details_tv_appliance_online.setText("在线");
            activity_device_details_tv_appliance_online.setTextColor(ContextCompat.getColor(mBaseActivity, R.color.lawn_green));
            activity_device_details_switch.setClickable(true);
        } else if (onlineStatus.equals("20")) {
            activity_device_details_tv_appliance_online_loading.setVisibility(View.GONE);
            activity_device_details_tv_appliance_online.setVisibility(View.VISIBLE);
            activity_device_details_tv_appliance_online.setText("离线");
            activity_device_details_tv_appliance_online.setTextColor(ContextCompat.getColor(mBaseActivity, R.color.red));
            activity_device_details_switch.setClickable(false);
        }

        if (status.equals("10")) {
            activity_device_details_img_switch_loading.setVisibility(View.GONE);
            activity_device_details_switch.setVisibility(View.VISIBLE);
            activity_device_details_switch.setChecked(true);
        } else if (status.equals("20")) {
            activity_device_details_img_switch_loading.setVisibility(View.GONE);
            activity_device_details_switch.setVisibility(View.VISIBLE);
            activity_device_details_switch.setChecked(false);
        }
    }

    //基本信息和设备状态
    protected void getApplianceDetails() {
        getApplianceMessage();
//        getApplianceStatus();
    }


    @OnClick(R.id.common_head_more)
    protected void moreClick() {
        final CustomPopupMenu.Builder builder = new CustomPopupMenu.Builder(this);
        builder.setIcon(moreIconList)
                .setTitle(moreTitleList)
                .isShowLine(true)
                .setItemLayoutParams(-2, -2)
                .setItemLayoutPadding(10, 10, 20, 20)
                .setContentView(common_head_more)
                .setOff(-(int) (common_head_more.getWidth() / DisplayHelper.DENSITY / 2.5), 0)
                .setOnMenuItemClickListener(new CustomPopupMenu.onMenuItemClickListener() {
                    @Override
                    public void onMenuItemClick(int itemPosition) {
                        switch (itemPosition) {
                            case 0:
                                EditDialog editDialog = new EditDialog(mBaseActivity);
                                editDialog.setOnAddClickListener(new EditDialog.OnAddClickListener() {
                                    @Override
                                    public void onAddClick(String name) {
                                        updateApplianceName(name);
                                    }
                                });
                                editDialog.show();
                                break;
                            case 1:
                                new CustomDialog.Builder(mBaseActivity)
                                        .setTitle("智能家居")
                                        .setMessage("要删除这个设备吗?")
                                        .setButton(DialogInterface.BUTTON_POSITIVE, "删除", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                deleteAppliance();
                                            }
                                        })
                                        .setButton(DialogInterface.BUTTON_NEGATIVE, "取消", null)
                                        .setCancelable(false)
                                        .create()
                                        .show();
                                break;
                            default:
                                break;
                        }
                        builder.dismiss();
                    }
                })
                .create()
                .show();
    }

    @Override
    public void onResume() {
        super.onResume();
        getApplianceDetails();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NettyBaseMsg nettyBaseMsg) {
        //家电状态根据对应的id处理
        NettyReplyStatusMsg nettyReplyStatusMsg = (NettyReplyStatusMsg) nettyBaseMsg;
        if (nettyReplyStatusMsg.getList() == null) {
            CustomTipDialog customTipDialog = new CustomTipDialog(this);
            customTipDialog.setMessage("中控端不在线，请检查连接");
            customTipDialog.setIconType(CustomTipDialog.ICON_TYPE_INFO);
            customTipDialog.show();
            updateApplianceStatus("20", "20");
        } else {
            List<DeviceModel> list = nettyReplyStatusMsg.getList();
            for (int i = 0; i < list.size(); i++) {
                String mClientId = list.get(i).getMemberId();
                String mDeviceId = list.get(i).getDeviceId();
                String mApplianceId = list.get(i).getApplianceId();
                Log.d(TAG, "onEventMainThread: " + mClientId + "==" + mDeviceId + "==" + mApplianceId);
                if ((mClientId.equals(AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone())) && mApplianceId.equals(applianceModel.getApplianceId())) {
                    updateApplianceStatus(list.get(i).getOnlineStatus() == null ? "20" : list.get(i).getOnlineStatus()
                            , list.get(i).getStatus() == null ? "20" : list.get(i).getStatus());
                }
            }
        }
    }

    //获取设备状态 1.上线状态 2.设备状态
    protected void getApplianceStatus(String deviceId, String applianceId) {
        String clientId = AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone();
        //组装 设备列表
        List<DeviceModel> list = new ArrayList<>();
        DeviceModel deviceModel = new DeviceModel();
        deviceModel.setMemberId(clientId);
        deviceModel.setDeviceId(deviceId);
        deviceModel.setApplianceId(applianceId);
        deviceModel.setOnlineStatus("20");
        deviceModel.setStatus("20");
        list.add(deviceModel);
        //获取
        NettyClient.getInstance().getApplianceStatus(clientId, deviceId, list);
//        updateApplianceStatus("10", "20");
    }

    //控制设备
    protected void controlApplianceStatus(String status, String params) {
        String clientId = AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone();
        //组装 设备列表
        List<DeviceModel> list = new ArrayList<>();
        DeviceModel deviceModel = new DeviceModel();
        deviceModel.setMemberId(clientId);
        deviceModel.setDeviceId(applianceModel.getMemberDeviceId());
        deviceModel.setApplianceId(applianceModel.getApplianceId());
        deviceModel.setApplianceType(applianceModel.getApplianceType());
        deviceModel.setStatus(status);
        if (params != null) {
            deviceModel.setParams(params);
        }
        list.add(deviceModel);
        //获取
        NettyClient.getInstance().controlApplianceStatus(clientId, applianceModel.getMemberDeviceId(), list);
    }
}
